//
//  FilesTableViewController.swift
//  ScreenRecordingDemo
//
//  Created by huangkun on 2020/10/26.
//

import UIKit
import AVKit

class FilesTableViewController: UITableViewController {
    
    var files:[HKSandboxFileModel] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "文件"

        tableView.delegate = self
        tableView.dataSource = self
        
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        
        getVideos()
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: compositeBtn)
    }
    
    func getVideos() {
        files = HKSandboxFileHandle.filesInDirectory(path: dirPath).sorted(by: { (model1, model2) -> Bool in
            let date1 = (model1.creatDate as Date?) ?? Date()
            let data2 = (model2.creatDate as Date?) ?? Date()
            
            return date1.compare(data2) == .orderedAscending
        })
        tableView.reloadData()
    }
    
    @objc private func compositeVideosAction(sender:UIButton) {
        if #available(iOS 11.0, *) {
            if !ScreenRecordManager.share.isRecording {

                do {
                    try HKSandboxFileHandle.creatDirectory(path: dirPath)
                    let filePath = dirPath + "/\(UUID().uuidString.replacingOccurrences(of: "-", with: "")).mp4"
                    ScreenRecordManager.share.compositeVideos(filePaths: files.map({$0.fullPath}), toPath: filePath) {[weak self] in
                        print("合成成功")
                        self?.getVideos()
                    } failed: { (error) in
                        print("===== error = \(error)")
                    }

                } catch let error {
                    print("error = \(error)")
                }
            }
        } else {
            // Fallback on earlier versions
        }
    }
    
    // MARK: - Table view data source

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return files.count
    }

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        let date = (files[indexPath.row].creatDate as Date?) ?? Date()
        let fomatter = DateFormatter()
        fomatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        
        let size = Double(files[indexPath.row].size) / 1024 / 1024
        
        cell.textLabel?.text = fomatter.string(from: date) + String(format: "    %.2lfM", size)
        return cell
    }
    
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
    
    override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        
        let delete = UITableViewRowAction(style: .destructive, title: "删除") { (action, index) in
            print("delete -=== ")
            try? FileManager.default.removeItem(atPath: self.files[index.row].fullPath)
            self.getVideos()
        }
        
        return [delete]
    }
    
    override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        return .delete
    }
    
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            print("delete")
        }
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = AVPlayerViewController()
        vc.player = AVPlayer(url: URL(fileURLWithPath: files[indexPath.row].fullPath))
        self.present(vc, animated: true, completion: nil)
    }
    
    private lazy var compositeBtn: UIButton = {
        let compositeBtn = UIButton(type: .custom)
        compositeBtn.setTitleColor(.red, for: .normal)
        compositeBtn.setTitleColor(.red, for: .selected)
        compositeBtn.setTitle("合成", for: .normal)
        compositeBtn.addTarget(self, action: #selector(compositeVideosAction(sender:)), for: .touchUpInside)
        compositeBtn.bounds = CGRect(x: 0, y: 0, width: 40, height: 40)
        return compositeBtn
    }()

}
